/**
 * 请求类
 */

import {
  AsyncStorage,
} from 'react-native';

import Toast from 'react-native-root-toast';
import Config from './config';

const Request = {};

Request.getToken = async function() {
  return await AsyncStorage.getItem(Config.token_key);
}
Request.getRequestOptions = async function(method) {
  var tokenData = await Request.getToken();
  var tokenData = JSON.parse(tokenData);
  var token = tokenData.access_token;
  console.log("___token: ", token);
  if (!token) {
    Toast.show("token missing...");
    return null;
  }
  let options = {
    method: method,
    headers: {
      "Accept": "application/json",
      "Content-Type": "application/json",
      "Authorization": "Bearer " + token,
    }
  }
  return options;
}


Request.get = async function(url, queryString) {
  let options = await Request.getRequestOptions("GET");
  console.log("requestOptions: ", options);
  if (!options) {
    return null;
  }
  if (queryString) {
      url += "?" + queryString;
  }
  return fetch(url, options)
  .then((response) => response.json())
  .catch((error) => {
    Toast.show("Request.get error: " + error.message);
  })
}

Request.post = async function(url, dataObject) {
  let options = await Request.getRequestOptions("POST");
  console.log("requestOptions: ", options, "body: ", dataObject);
  if (!options) {
    return null;
  }

  options.body = JSON.stringify(dataObject)
  
  return fetch(url, options)
  .then((response) => response.json())
  .catch((error) => {
    Toast.show("Request.post error: " + error.message);
  })
}

module.exports = Request;